package com.liwang.lanouhn.nvshengo.activities;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.liwang.lanouhn.nvshengo.Info.DataInfo;
import com.liwang.lanouhn.nvshengo.Info.InfoEvent;
import com.liwang.lanouhn.nvshengo.Info.LiveInfo;
import com.liwang.lanouhn.nvshengo.Info.VideoInfo;
import com.liwang.lanouhn.nvshengo.R;
import com.liwang.lanouhn.nvshengo.adapter.ViewPagerLivesAdapter;
import com.liwang.lanouhn.nvshengo.fragments.NumberListFragment;
import com.liwang.lanouhn.nvshengo.fragments.TheHostFragment;
import com.liwang.lanouhn.nvshengo.view.BarrageRelativeLayout;
import com.superplayer.library.SuperPlayer;

import org.greenrobot.eventbus.EventBus;

import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by lanouhn on 2016/10/15.
 */
public class CosmeticLiveActivity extends AppCompatActivity implements SuperPlayer.OnNetChangeListener {
    private SuperPlayer live_superplayer;
    private TabLayout tabLayout;
    private ViewPager viewPager;
    private List<String> tabNames;
    private List<Fragment> fragments;
    private ViewPagerLivesAdapter viewPagerLivesAdapter;
    private RelativeLayout rl_subscribe;
    private TextView tv_subscribe,tv_view;
    private ImageView iv_subscribe;
    private String liveurl;
    private VideoInfo info;
    private LiveInfo liveInfo;
    private DataInfo dataInfo;
    private String dataurl;
    private int times;
    private BarrageRelativeLayout barrageRelativeLayout;
    String[] itemText = {"主播好漂亮...", "你是哪里人啊", "主播你的胸好大啊","都在干嘛呢","喜欢主播的点下赞","主播声音好好听，，，",
            "这是我老婆，，", "李晓峰我知道你在看，别装啦", "这么丑还能出来当主播", "主播萌的有...点二", "主播跳个舞、、、吧",
            "主播唱...个歌呗","水饺多少钱一晚...","你柰子这么大，你爸爸知道吗？","你可要摸着良心直播哈！！！！","都瞪大眼睛，，主播要直播下面啦...",
            "主播发福利啦，，，","fans群号多少啊，主播加我QQ啊啊啊！！","打算了可；实例；‘","多少级了可怕；离开； ","搜客；’。‘吗","好高好高的深V很快就"};

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        int flag= WindowManager.LayoutParams.FLAG_FULLSCREEN;
        Window window=getWindow();
        window.setFlags(flag,flag);
        setContentView(R.layout.activity_cosmeticlive);
        initView();

        getDataWeb();
    }

    private void initView() {
        rl_subscribe= (RelativeLayout) findViewById(R.id.rl_subscribe);
        tv_subscribe= (TextView) findViewById(R.id.tv_subscribe);
        tv_view= (TextView) findViewById(R.id.tv_view);
        iv_subscribe= (ImageView) findViewById(R.id.iv_subscribe);
        tabLayout = (TabLayout)findViewById(R.id.tab_cosmeticlives);
        viewPager = (ViewPager)findViewById(R.id.vp_cosmeticlives);
        live_superplayer = (SuperPlayer) findViewById(R.id.live_superplayer);
        barrageRelativeLayout= (BarrageRelativeLayout)findViewById(R.id.butttonPanel);
        LinkedList<String> texts =new LinkedList<String>();
        for (int i=0;i<itemText.length;i++){
            texts.add(itemText[i]);
        }
        barrageRelativeLayout.setBarrageTexts(texts);
        barrageRelativeLayout.show(BarrageRelativeLayout.RANDOM_SHOW);
    }


    private void getDataWeb() {
        info= (VideoInfo) getIntent().getSerializableExtra("videoInfo");
        String id =info.getId();
        String domain =info.getDomain();
        liveurl = "http://livestream.plu.cn/live/GetLivePlayUrl?roomId="+id+"&appId=4001&version=3.6.4&device=4&packageId=1";
        dataurl="http://roomapicdn.plu.cn/room/RoomAppStatusV2?domain="+domain+"&version=3.7.0&device=4&packageId=1";
        new Thread(new Runnable() {
            @Override
            public void run() {
                OkHttpClient client =new OkHttpClient();
                final Request request =new Request.Builder().url(liveurl).build();
                Call call =client.newCall(request);
                call.enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {

                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                       String result =response.body().string();
                        Gson gson =new Gson();
                        liveInfo=gson.fromJson(result,LiveInfo.class);
                        if (liveInfo.getPlayLines().size()>0){
                            handler.sendEmptyMessage(1);
                        }else {
                            handler.sendEmptyMessage(0);
                        }

                    }
                });
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                OkHttpClient client =new OkHttpClient();
                final Request request =new Request.Builder().url(dataurl).build();
                Call call =client.newCall(request);
                call.enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {

                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        String result =response.body().string();
                        Gson gson =new Gson();
                        dataInfo=gson.fromJson(result,DataInfo.class);
                        if (dataInfo!=null){
                            handler.sendEmptyMessage(2);
                        }else {
                            handler.sendEmptyMessage(0);
                        }

                    }
                });

            }
        }).start();
    }
    private Handler handler =new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    Toast.makeText(CosmeticLiveActivity.this, "网络请求失败", Toast.LENGTH_SHORT).show();
                    break;
                case 1:
                    String path = liveInfo.getPlayLines().get(0).getUrls().get(0).getSecurityUrl();
                    live_superplayer.setLive(true);//设置该地址的类型,false为视频，true为直播
                    live_superplayer.setNetChangeListener(true)//设置监听手机网络的变化
                            .setOnNetChangeListener(CosmeticLiveActivity.this)//实现网络变化的回调
                            .onPrepared(new SuperPlayer.OnPreparedListener() {
                                @Override
                                public void onPrepared() {
                                    /**
                                     * 监听视频是否已经准备完成开始播放。（可以在这里处理视频封面的显示跟隐藏）
                                     */
                                }
                            }).onComplete(new Runnable() {
                        @Override
                        public void run() {
                            /**
                             * 监听视频是否已经播放完成了。（可以在这里处理视频播放完成进行的操作）
                             */

                        }
                    }).onInfo(new SuperPlayer.OnInfoListener() {
                        @Override
                        public void onInfo(int what, int extra) {
                            /**
                             * 监听视频的相关信息。
                             */
                        }
                    }).onError(new SuperPlayer.OnErrorListener() {
                        @Override
                        public void onError(int what, int extra) {
                            /**
                             * 监听视频播放失败的回调
                             */

                        }
                    }).setTitle(path)//设置视频的titleName
                            .play(path);//开始播放视频
                    live_superplayer.setScaleType(SuperPlayer.SCALETYPE_FILLPARENT);//设置视频显示的方式
                    live_superplayer.setPlayerWH(0,
                            live_superplayer.getMeasuredHeight());//设置竖屏的时候屏幕的高度，如果不设置会切换后按照16:9的高度重置
                    break;
                case 2:
                    tv_view.setText(dataInfo.getBaseRoomInfo().getSubscribeCount()+"");

                tabNames = new ArrayList<>();
                tabNames.add("主播");
                tabNames.add("排行榜");
                fragments = new ArrayList<>();
                TheHostFragment thehost =TheHostFragment.newInstants(dataInfo);
                fragments.add(thehost);
                NumberListFragment numberlist =NumberListFragment.newInstants(info);
                fragments.add(numberlist);
                viewPagerLivesAdapter = new ViewPagerLivesAdapter(getSupportFragmentManager(), tabNames, fragments);
                viewPager.setAdapter(viewPagerLivesAdapter);
                tabLayout.setupWithViewPager(viewPager );
                rl_subscribe.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if (tv_subscribe.getText().equals("订阅主播")) {
                            iv_subscribe.setBackgroundResource(R.mipmap.ic_zhibo_yidingyue_normal);
                            tv_subscribe.setText("已订阅");
                            Toast.makeText(CosmeticLiveActivity.this, "成功订阅该房间 !", Toast.LENGTH_SHORT).show();
                            tv_view.setText((dataInfo.getBaseRoomInfo().getSubscribeCount()+1)+"");
                            times = 1;
                            EventBus.getDefault().post(new InfoEvent(info));
                        } else {
                            iv_subscribe.setBackgroundResource(R.mipmap.ic_zhibo_weidingyue_normal);
                            tv_subscribe.setText("订阅主播");
                            Toast.makeText(CosmeticLiveActivity.this, "退订成功", Toast.LENGTH_SHORT).show();
                            tv_view.setText(dataInfo.getBaseRoomInfo().getSubscribeCount()+"");
                            times = 0;
//                            EventBus.getDefault().post(new ReduceEvent(info));
                        }
                    }
                });
                    break;
            }

        }
    };



    @Override
    protected void onDestroy() {
        super.onDestroy();
        live_superplayer.onDestroy();
    }

    /**
     * 网络链接监听类
     */
    @Override
    public void onWifi () {
        Toast.makeText( this, "当前网络环境是WIFI", Toast.LENGTH_SHORT ).show();
    }

    @Override
    public void onMobile () {
        Toast.makeText( this, "当前网络环境是手机网络", Toast.LENGTH_SHORT ).show();
    }

    @Override
    public void onDisConnect () {
        Toast.makeText( this, "网络链接断开", Toast.LENGTH_SHORT ).show();
    }

    @Override
    public void onNoAvailable () {
        Toast.makeText( this, "无网络链接", Toast.LENGTH_SHORT ).show();
    }



}
